/**
 * @file hoc.jsx.
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  Component,
  PropTypes
} from "react";
import {findDOMNode} from 'react-dom';
import {fetch} from '../renderer';
import * as assign from 'object-assign';

export const Enhance = (sourceKey= 'source') => ComposedComponent => class FetchSource extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      source: props[sourceKey],
      sourceFetching: !!props[sourceKey] && !/^\$/.test(props[sourceKey])
    };

    this.fetchSource = this.fetchSource.bind(this);
  }

  fetchSource(values) {
    const {
      locals,
      data
    } = this.props;
    const source = this.state.source;
    this.setState({
      sourceFetching: true
    }, () => fetch(source, values, 'get', assign({}, locals, data))
      .then(ret => this.setState({
        sourceError: false,
        sourceFetching: false,
        sourceData: ret.data
      }))
      .catch(error => this.setState({
        sourceError: error,
        sourceFetching: false
      })))
  }


  render() {
    return (
      <ComposedComponent {...this.props} {...this.state} fetchSource={this.fetchSource} />
    )
  }
};

export default Enhance;